<?php

declare(strict_types=1);

namespace App\Http\Api\Middleware;

use App\Http\Api\CurrentUser;
use App\Request\auth\Service\Jwt\JwtService;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Mockery\Exception;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

/**
 * C端WebSocket权限中间件
 * @Middleware(priority=1)
 */
class AuthWebSocketMiddleware implements MiddlewareInterface
{
    public function __construct(
        protected readonly ContainerInterface $container,
        protected readonly HttpResponse       $response,
        protected readonly JwtService         $jwtService,
        protected readonly CurrentUser        $currentUser,
    )
    {
    }

    /**
     * @throws \Exception
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $token = $this->jwtService->setGuard('user')->getTokenFromRequest($request);
        try {
            $payload = $this->jwtService->setGuard('user')->verifyToken($token);
            if (!$payload) {
                throw new Exception('请先登录');
            }
            // 获取当前用户
            $this->currentUser->setUser((int)$payload->sub);

        } catch (\Throwable $e) {
           //阻止websocket连接
            throw new Exception($e->getMessage());
        }

        return $handler->handle($request);
    }
}
